package com.example.calcite.xml;

import org.apache.calcite.jdbc.CalciteConnection;
import org.apache.calcite.schema.SchemaPlus;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Properties;

public class DynamicXmlDemo {
    public static void main(String[] args) throws Exception {
        // 创建 XML 服务
        XmlService xmlService = new HttpXmlService("http://api.example.com");
        
        // 示例 SQL
        String sql = "SELECT e.name, d.name as dept_name " +
                    "FROM XML.12345.employees e " +
                    "JOIN XML.12345.departments d " +
                    "ON e.dept_id = d.id " +
                    "WHERE e.age > 30";
        
        // 提取 XML ID
        String xmlId = XmlSqlParser.extractXmlId(sql);
        
        // 创建 Calcite 连接
        Properties info = new Properties();
        info.setProperty("lex", "MYSQL");
        
        try (Connection connection = DriverManager.getConnection("jdbc:calcite:", info)) {
            CalciteConnection calciteConnection = connection.unwrap(CalciteConnection.class);
            SchemaPlus rootSchema = calciteConnection.getRootSchema();
            
            // 注册动态 XML schema
            rootSchema.add("XML", new DynamicXmlSchema(xmlId, xmlService));
            
            // 执行查询
            try (Statement stmt = connection.createStatement()) {
                ResultSet rs = stmt.executeQuery(sql);
                while (rs.next()) {
                    System.out.println(rs.getString("name") + ", " + 
                                     rs.getString("dept_name"));
                }
            }
        }
    }
}